package com.yboot.service.boot.test.websocket;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import com.yboot.stater.websocket.core.api.DestinationResolveApi;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Websocket获取token
 *
 * @author yangcs
 * @date 2025/8/27
 */
public class SaTokenDestinationResolveApiImpl implements DestinationResolveApi {
    @Override
    public List<String> getPlatformSubscriberTokens(String platform) {

        // 搜索所有Token值（可根据设备标识过滤）
        List<String> allTokens = StpUtil.searchTokenValue("", 0,-1, true);

        // 过滤出指定设备的Token
        return allTokens.stream()
                .filter(token -> isPlatformToken(platform, token))
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getPlatformSubscriberTokens(String platform, String userId) {
        List<String> subscriberTokens = getSubscriberTokens(userId);

        return subscriberTokens.stream().filter(token -> isPlatformToken(platform, token)).collect(Collectors.toList());
    }
    /**
     * 判断 token 是否属于指定平台
     */
    private boolean isPlatformToken(String platform, String token) {
        String loginDevice = StpUtil.getLoginDeviceByToken(token);
        return StringUtils.hasLength(loginDevice) && loginDevice.equals(platform);
    }


    @Override
    public List<String> getPlatformSubscriberTokens(String platform, List<String> userIds) {
        List<String> subscriberTokens = getSubscriberTokens(userIds);

        return subscriberTokens.stream().filter(token -> isPlatformToken(platform, token)).collect(Collectors.toList());
    }

    @Override
    public List<String> getSubscriberTokens(String userId) {
        return StpUtil.getTokenValueListByLoginId(userId);
    }

    @Override
    public List<String> getSubscriberTokens(List<String> userIds) {
        List<String> tokenValues = new ArrayList<>();
        userIds.forEach(id -> tokenValues.addAll(getSubscriberTokens(id)));

        return tokenValues.stream().filter(StringUtils::hasLength).collect(Collectors.toList());
    }
}
